<template>
  <page-header-wrapper :title="false">
    <div class="Role">
      <a-spin tip="加载中..." class="position" v-if="roleLoading"> </a-spin>
      <a-modal
        width="1000px"
        v-model="modleVisible"
        :title="isAdd ? '新增消息' : '编辑消息'"
        @cancel="() => (this.modleVisible = false)"
        :confirm-loading="formButtonDisableFlag"
        @ok="onSubmit"
      >
        <div id="modalContent">
          <div class="formAspin" v-if="editWaitForLoading">
            <a-spin />
          </div>
          <div class="modalContentForm">
            <a-form-model
              ref="formRef"
              :model="form"
              :rules="rules"
              :label-col="{ span: 3 }"
              :wrapper-col="{ span: 21 }"
            >
              <a-row type="flex" justify="space-between">
                <a-col :span="24">
                  <Input :form="form" label="消息标题" prop="title" placeholder="请输入消息标题"></Input>
                </a-col>
                <a-col :span="24">
                  <Textarea
                    :form="form"
                    label="消息内容"
                    prop="content"
                    :rows="6"
                    placeholder="请输入消息内容"
                  ></Textarea>
                </a-col>
                <a-col :span="24">
                  <Textarea :form="form" label="提示" prop="remark" :rows="4" placeholder="请输入提示"></Textarea>
                </a-col>
              </a-row>
            </a-form-model>
          </div>
        </div>
      </a-modal>
      <a-modal
        width="50%"
        v-model="parameterVisible"
        title="发送消息"
        @cancel="() => (this.parameterVisible = false)"
        destroyOnClose
      >
        <div id="modalContent2">
          <IssueUser :sendTitleId="sendTitleId" @closeParameter="closeParameter"></IssueUser>
        </div>
        <template slot="footer">
          <Button
            type="reset"
            label="关闭"
            @click="
              () => {
                this.parameterVisible = false;
              }
            "
          ></Button>
        </template>
      </a-modal>
      <typicalSearch ref="insideSearch" :searchConfig="searchConfig" @searchMethod="getTableData"></typicalSearch>
      <div class="table">
        <div class="tableTitle">
          <div class="title">消息管理</div>
          <div class="addButton">
            <a-button type="primary" @click="handleEdit('modleVisible')"> 新增消息 </a-button>
          </div>
        </div>
        <div class="tableList">
          <typicalTable
            ref="insideTable"
            :tableConfig="tableConfig"
            :tableData="tableData"
            @getTableData="getTableData"
          >
            <template v-slot="slotProps">
              <Button
                v-if="slotProps.record.status != '-1'"
                label="编辑"
                @click="handleEdit('modleVisible', slotProps.record)"
              ></Button>
              <a-popconfirm
                slot="action"
                title="此操作将删除该条数据，是否继续?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(slotProps.record)"
              >
                <Button type="stop" v-if="slotProps.record.status != '-1'" label="删除"></Button>
              </a-popconfirm>
              
              <Button label="站内消息" v-if="slotProps.record.status == '0'" @click="handleEdit('parameterVisible', slotProps.record)"></Button>
              <a-popconfirm
                title="此操作将发送信息至全平台用户，是否继续?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleSend(slotProps.record,1)"
              >
                <Button type="stop" label="系统消息" v-if="slotProps.record.status == '0'"> </Button>
              </a-popconfirm>
            </template>
          </typicalTable>
        </div>
      </div>
    </div>
  </page-header-wrapper>
</template>
<script>
import moment from 'moment';
import typicalSearch from '@/components/typicalSearch';
import typicalTable from '@/components/typicalTable';
import Input from '@/components/typicalControl/Input';
import treeSelect from '@/components/typicalControl/treeSelect';
import Select from '@/components/typicalControl/select';
import Button from '@/components/typicalControl/button';
import Textarea from '@/components/typicalControl/textarea';
import IssueUser from './IssueUser';

import { listMessages } from '@/api/cabin';
export default {
  name: 'MessageManagement',
  components: {
    typicalSearch: typicalSearch,
    typicalTable: typicalTable,
    Input: Input,
    Textarea: Textarea,
    treeSelect: treeSelect,
    Select: Select,
    Button: Button,
    IssueUser: IssueUser,
  },
  data() {
    return {
      isAdd: false,
      parameterVisible: false,
      formButtonDisableFlag: false, // 表单确定禁用按钮 防止多次点击多次保存
      editWaitForLoading: false, // 加载编辑回显数据等待Loading
      roleLoading: false, // 加载表格的loading
      modleVisible: false, // 控制弹框
      form: {
        title: undefined,
        content: undefined,
        remark: undefined,
        // isEnable: 1,
        // isSystem: 0
      },
      rules: {
        // 规则验证
        title: [
          { required: true, message: '请输入消息标题', trigger: 'blur' },
          { max: 255, message: '最大长度不能超过255个字', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入消息内容', trigger: 'blur' },
          { max: 255, message: '最大长度不能超过255个字', trigger: 'blur' },
        ],
        remark: [{ max: 255, message: '最大长度不能超过255个字', trigger: 'blur' }],
      },
      // 搜索组件配置
      searchConfig: {
        formItemList: [
          {
            type: 'input',
            prop: 'searchTitle',
            value: '',
            label: '标题',
          },
          {
            type: 'input',
            prop: 'searchContent',
            value: '',
            label: '内容',
          },
          {
            type: 'select',
            prop: 'searchStatus',
            value: '',
            label: '状态',
            optList: [
              { code: '1', name: '已发送' },
              { code: '0', name: '未发送' },
              { code: '-1', name: '删除' },
            ],
          },
        ],
        parent: this,
      },
      // 列表组件配置
      tableConfig: {
        columns: [
          {
            title: '标题',
            dataIndex: 'title',
            ellipsis: true,
          },
          {
            title: '消息内容',
            dataIndex: 'content',
            ellipsis: true,
          },
          {
            title: '提示',
            dataIndex: 'remark',
            ellipsis: true,
          },
          {
            title: '状态',
            dataIndex: 'status',
            ellipsis: true,
            customRender: this.formatterStatus,
          },
          {
            title: '创建人',
            dataIndex: 'userName',
            ellipsis: true,
          },
          {
            title: '创建时间',
            dataIndex: 'createTime',
            ellipsis: true,
            customRender: this.formatterTime,
          },
          {
            title: '操作',
            scopedSlots: { customRender: 'action' },
          },
        ],
        pageSize: this.$store.state.user.defaultPaginationPagesize,
        pageSizeOptions: this.$store.state.user.defaultPaginationOptions,
        parent: this,
      },
      // 列表组件数据
      tableData: {
        records: [],
        total: 0,
      },
      sendTitleId: null,
    };
  },
  created() {},
  mounted() {
    this.$refs.insideSearch.searchInfo();
  },
  methods: {
    /**
     * [getTableData 获取表格数据]
     * @param  {[type]} searchParam [搜索条件]
     * @return {[type]}             [description]
     */
    getTableData(searchParam) {
      this.roleLoading = true;
      let searchData = searchParam ? { ...searchParam } : {};
      let params = {
        pageNum: searchData.pageNumber ? searchData.pageNumber + 1 : 1,
        pageSize: searchData.pageSize ? searchData.pageSize : 10,
        content: searchData.searchContent ? searchData.searchContent : '',
        title: searchData.searchTitle ? searchData.searchTitle : '',
        remark: searchData.searchTips ? searchData.searchTips : '',
        status: searchData.searchStatus ? searchData.searchStatus : '',
      };
      listMessages(`/selectMessagePageList`, 'get', params)
        .then((res) => {
          if (res.code === 200 && res.data.records) {
            this.tableData = res.data;
          } else {
            this.tableData.records = [];
            this.tableData.total = 0;
          }
        })
        .finally(() => {
          this.roleLoading = false;
        });
    },
    closeParameter() {
      this.parameterVisible = false;
      this.getTableData();
    },
    /**
     * @description: 新增编辑消息表单提交
     */
    onSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.formButtonDisableFlag = true;
          if (this.form.id) {
            this.editRole(this.form);
          } else {
            this.roleAdd(this.form);
          }
        } else {
          return false;
        }
      });
    },

    /**
     * [initializationForm 初始化form数据]
     * @return {[type]} [description]
     */
    initializationForm() {
      return {
        title: undefined,
        content: undefined,
        remark: undefined,
        // isEnable: 1,
        // isSystem: 0
      };
    },

    /**
     * @description: 新增消息权限
     * @param {object} addRoleParam 表单参数
     */
    roleAdd(addRoleParam) {
      listMessages('/insertMessage', 'post', addRoleParam)
        .then((res) => {
          if (res.code == 200) {
            this.formSuccessOperation(res);
          }
        })
        .finally(() => {
          this.formButtonDisableFlag = false;
        });
    },

    /**
     * @description: 编辑消息权限
     * @param {object} editRoleParam 表单参数
     */
    editRole(editRoleParam) {
      let { id, title, content, remark } = { ...editRoleParam };
      listMessages('/updateMessage', 'put', { id, title, content, remark })
        .then((res) => {
          if (res.code == 200) {
            this.formSuccessOperation(res);
          }
        })
        .finally(() => {
          this.formButtonDisableFlag = false;
        });
    },

    /**
     * @description: 表单新增编辑成功后的公共的代码 （消息提示 搜索框重置 请求表格数据）
     * @param {object} successFormData 表单请求成功后返回的对象
     */
    formSuccessOperation(successFormData) {
      this.$message.success(successFormData.message);
      this.modleVisible = false;
      this.$refs.insideTable.updateListData();
    },

    /**
     * @description: 新增或编辑或发送
     * @param {object} row          表格某一行的数据对象
     * @param {object} instructions 显示弹窗
     */
    handleEdit(instructions, row) {
      this.isAdd = true;
      this[instructions] = true;
      this.form = this.initializationForm();
      if (row) {
        this.isAdd = false;
        this.sendTitleId = row.id;
        this.form = Object.assign(this.form, row);
        // this.editWaitForLoading = true;
        // // 根据ID请求相应消息的权限 进行回显
        // loadMessageById({ id: row.id })
        //   .then(res => {
        //     if (res.code === 200) {
        //       this.form = Object.assign(this.form, res.data);
        //     }
        //   })
        //   .finally(() => {
        //     this.editWaitForLoading = false;
        //   });
      }
    },

    /**
     * @description: 点击删除
     * @param {object} roleTableRowData 格某一行的数据对象
     */
    handleDelete(roleTableRowData) {
      listMessages(`/deleteById?id=${roleTableRowData.id}`, 'put').then((res) => {
        if (res.code === 200) {
          this.$message.success(res.message);
          this.$refs.insideTable.updateListData();
        }
      });
    },
    formatterTime(val) {
      return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : '';
    },
    formatterStatus(val) {
      let statusData = {
        1: '已发送',
        0: '未发送',
        '-1': '删除',
      };
      return statusData[val];
    },
    handleSend(row,type) {
      this.modleVisible = true;
      let {id,title,content,
        remark}= {...row};
      listMessages(`/updateMessageSendList?userAll=${type}&userIds=`, 'post', {id,title,content,
        remark})
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
            this.$refs.insideTable.updateListData();
          }
        })
        .finally(() => {
          this.modleVisible = false;
        });
    },
  },
};
</script>

<style lang="less" scoped>
.Role {
  width: 100%;
  height: calc(100vh - 150px);
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  position: relative;
  .position {
    width: 100%;
    height: 100%;
    background: white;
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }
  .table {
    flex: 1;
    background: white;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    .tableTitle {
      width: 100%;
      height: 64px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ececec;
      padding: 0 20px;
      margin-bottom: 10px;
      .title {
        width: 80%;
        height: 100%;
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: 550;
      }
      .addButton {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }
    .tableList {
      // max-height: calc(100vh - 380px);
      // overflow: auto;
      /deep/ .tableScroll {
        max-height: calc(100vh - 380px);
        overflow: auto;
      }
    }
  }
}
#modalContent {
  width: 100%;
  height: 340px;
  position: relative;
  .formAspin {
    position: absolute;
    width: 100%;
    height: 340px;
    background: #ececec;
    border-radius: 4px;
    z-index: 999;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
#modalContent2 {
  width: 100%;
  height: 600px;
  overflow: auto;
  position: relative;
  .formAspin {
    position: absolute;
    width: 100%;
    height: 600px;
    background: #ececec;
    border-radius: 4px;
    z-index: 999;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
/deep/ .ant-col-20 .ant-col-4{
  width: 20.666667%;
}
</style>
